/**
 * udp 广播服务端，接收端
*/



#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define PORT 5555

static int init_udp_server(void)
{
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (0 > socket)
    {
        perror("socket error: ");
        exit(EXIT_FAILURE);
    }

    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(PORT);
    serverAddr.sin_addr.s_addr = INADDR_ANY;

    int opt = 1;
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
    {
        perror("setsockopt error: ");
        exit(EXIT_FAILURE);
    }

    if (setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &opt, sizeof(opt)) < 0)
    {
        perror("setsockopt error: ");
        exit(EXIT_FAILURE);
    }

    if (bind(sockfd, (struct sockaddr *)&serverAddr, sizeof(struct sockaddr)) < 0)
    {
        perror("bind error: ");
        exit(EXIT_FAILURE);
    }

    return sockfd;
}

static void out_client_info(struct sockaddr_in clientAddr)
{
    char *ip = inet_ntoa(clientAddr.sin_addr);
    unsigned short port = ntohs(clientAddr.sin_port);
    printf("Connection from %s:%d\n", ip, port);
}



int main()
{
    int sockfd = init_udp_server();

    while (1)
    {
        char buf[1024] = {0};
        struct sockaddr clientAddr;
        socklen_t addrlen = sizeof(struct sockaddr);
        ssize_t len = recvfrom(sockfd, buf, 1024, 0, &clientAddr, &addrlen);

        if (0 >= len)
        {
            break;
        }

        struct sockaddr_in cAddr = *((struct sockaddr_in *)&clientAddr);

        out_client_info(cAddr);

        printf("recv from client: %s\n", buf);

       
    }

    close(sockfd);
    return 0;
}